import React, { Component } from "react";
import ReactDOM from 'react-dom';
import { TransitionGroup, CSSTransition } from "react-transition-group";
import style from "./style.module.scss";
import Notice from "./Notice";

class Notification extends Component {
  constructor(props) {
    super(props);
    this.state = {
      notices: []
    };
  }

  getkey = () => {
    const { notices } = this.state;
    return `notice_${new Date().getTime()}_${notices.length}`;
  };

  add = notice => {
    const { notices } = this.state;
    let arr = notices;
    notice.key = this.getkey(notices);
    if (notices.every(item => item.key !== notice.key)) {
      arr[0] = notice;
      this.setState({
        notices: arr
      });
      if (notice.duration > 0) {
        setTimeout(() => {
          this.remove(notice.key);
        }, notice.duration);
      }
    }
    return () => {
      this.remove(notice.key);
    };
  };

  remove = key => {
    this.setState(prevnotices => ({
      notices: prevnotices.notices.filter(notice => {
        if (notice.key === key) {
          if (notice.onClose) notice.onClose();
          return false;
        } else {
          return true;
        }
      })
    }));
  };

  render() {
    const { notices } = this.state;
    return (
      <TransitionGroup className={style.toast_notification}>
        {notices.map(notice => (
          <CSSTransition
            key={notice.key}
            timeout={300}
            className={[`${style.toast_notice_wrapper}`, `${style.notice}`].join(" ")}
          >
            <Notice {...notice} />
          </CSSTransition>
        ))}
      </TransitionGroup>
    );
  }
}

export default function createNotification() {
    const div = document.createElement('div');
    document.body.appendChild(div);
    const notification = ReactDOM.render(<Notification />, div);
    return {
        add(notice) {
            return notification.add(notice)
        },
        destory() {
            ReactDOM.unmountComponentAtNode(div)
            document.body.removeChild(div)
        }
    }
}